package poo.biblioteca.bd;

import biblioteca.excepciones.ExcepcionDeBD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.prefs.Preferences;

public class DBManager {

    private static Preferences preferencias;

    public static void setPreferencias(Preferences preferencias) throws ExcepcionDeBD {
        DBManager.preferencias = preferencias;
    }
    private String connectionUrl;
    private String host;
    private String protocol;
    private String dbName;
    private String user;
    private String password;
    private static DBManager dbManager;

    public static DBManager getInstancia() throws ExcepcionDeBD {
         if (dbManager == null) {
            dbManager = new DBManager(preferencias);
        }
        return dbManager;
    }

    public Connection getConnection(String connectionUrl) throws SQLException {
        return DriverManager.getConnection(connectionUrl);
    }

    public Connection getConnection() throws SQLException {
        leerInfoDePreferencias();
        return DriverManager.getConnection(connectionUrl);
    }

    public void limpiarConexion(Connection conexion) throws SQLException {
        conexion.close();
        conexion = null;
    }

    private DBManager(String connectionUrl) throws ExcepcionDeBD {
        this.connectionUrl = connectionUrl;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            throw new ExcepcionDeBD("No se puede cargar el driver de la BD");
        }
    }

    private DBManager(Preferences prefs) throws ExcepcionDeBD {

        leerInfoDePreferencias();

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            throw new ExcepcionDeBD("No se puede cargar el driver de la BD");
        }

    }

    private void leerInfoDePreferencias() {
        host = preferencias.get("Host", "localhost");
        protocol = preferencias.get("Protocol", "3306");
        dbName = preferencias.get("DBName", "biblioteca");
        user = preferencias.get("User", "root");
        password = preferencias.get("Password", "");
        connectionUrl = "jdbc:mysql://" + host + "/"
                + dbName + "?"
                + "user=" + user + "&"
                + "password=" + password;
    }
}
